import { throttle } from '../../utils/util'
import { commonApi } from '../../api/index';
import { wxLogin } from "../../utils/wxLogin";
Component({
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    pagesType: {
      type: String,
      value: "",
    },
  },
  data: {
    showLoginPopup: false,
  },
  methods: {
    onClose() {
      this.setData({
        show: false,
      });
    },
    onShowLoginPopup() {
      this.setData({
        showLoginPopup: true,
      });
    },
    getPhoneNumber: throttle(function (e) {
      const self = this
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        console.log(e.detail)
        commonApi.getPhoneInfo({
          code: e.detail.code
        }).then( async (resp) => {
          await commonApi.updateUserInfo({ phone: resp.phoneNumber })
          // await this.getUserInfo()
          await self.phoneLogin(resp)
          this.triggerEvent("onClick", resp);
          // var reg = /(\d{3})\d*(\d{4})/
          // this.setData({
          //   receiver_phone: resp.purePhoneNumber.replace(reg, '$1****$2')
          // });
        });
      }
    }),
    async phoneLogin(resp) {
      const self = this
       wx.login({
        success (res) {
          if (res.code) {
            //发起网络请求
            self.miniProgramLogin(res.code , resp)
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },
    async miniProgramLogin(code, resp){
      const res = await commonApi.miniProgramLogin({ 
        code
       })
      wx.setStorageSync("token", `Bearer ${res.token}`)
      wx.setStorageSync("code", code)
      wx.setStorageSync("openid", res.openid)
      this.triggerEvent("onClick", resp);
    },
    async onClick(e){
      this.onClose()
      this.triggerEvent("onClick", e.detail);
    },
    async getUserInfo() {
      try {
        let res = await commonApi.getUserInfo()
        if(res?.employee_info?.id){
          await wxLogin()
        }
      } catch (e) { }
    },
  },
});
